package com.xiaohei.crm.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.lang.UUID;
import com.xiaohei.crm.dao.vo.ValidateCodeVo;
import com.xiaohei.crm.service.ValidateCodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * ClassName: ValidateCodeServiceImpl
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/6/25 21:30
 * Version 1.0
 */
@Service
@RequiredArgsConstructor
public class ValidateCodeServiceImpl implements ValidateCodeService {
    private final StringRedisTemplate stringRedisTemplate;
    /**
     * 生成图片验证码
     *
     * @return
     */
    @Override
    public ValidateCodeVo generateValidateCode() {
        //1. 通过工具生成图片验证码
        //hutool
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 2);
        String codeValue = circleCaptcha.getCode();  //4位验证码的具体值
        String imageBase64 = circleCaptcha.getImageBase64(); //返回图片验证码，base64编码

        //2. 把验证码存到redis中  设置key：uuid  value：验证码值
        //设置过期时间
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        stringRedisTemplate.opsForValue().set("user:validate" + key,
                codeValue,
                5,
                TimeUnit.MINUTES);

        //3. 返回ValidateCodeVo
        ValidateCodeVo vo = new ValidateCodeVo();
        vo.setCodeKey(key);  //redis中存储数据的key
        vo.setCodeValue("data:image/png;base64," + imageBase64);
        return vo;
    }
}
